package com.qf.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.AccessDeniedHandler;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true,jsr250Enabled = true)
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private AccessDeniedHandler myAccessDenied;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    }

//    swagger资源放行
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/swagger-ui.html/**","/css/**","/images/**","/plugins/**");
        super.configure(web);
    }

//    资源访问权限定义
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/user/login","/user/check").permitAll().anyRequest().authenticated();
        http.addFilter(new MyBasicAuthenticationFilter(authenticationManagerBean()));
//        禁用csrf
        http.csrf().disable();

//        解决跨域
        http.cors();

//        自定义403异常
        http.exceptionHandling().accessDeniedHandler(myAccessDenied);
    }
}
